package server;

import java.io.IOException;
import java.net.*;
import java.util.*;

import robot.*;
import video.*;

import common.HitInformation;
import common.Shared;
import common.RobotInformation;



public class Server
{
	private static final int 
			DEFAULT_PORT = 9069;
	
	private static Vector< ServerHandler > handlers = 
			new Vector< ServerHandler >(5);
	
	private static BlueT bt = new BlueT();
	
	private videoStream vs = null;
	
	/** F T P _ S e r v e r (   )
	* ------------------------------------------------------------------------
	*   Creates a new FTP_Handler thread for every client trying to connect.
	*/
	public Server
		( int listenPort )
	{
		ServerSocket server = null;
		int port = ( listenPort <= 1024 ? DEFAULT_PORT : listenPort );
		
		try {
			server = new ServerSocket
					( port );
			System.out.println( "Server listening on port " + port );
		}
		catch( IOException e )
		{
			System.out.println
					( " ** FATAL ERROR: Could not create server socket! " +
					  "Aborting. **" );
			System.exit( 1 );
		} 
		
		
		// Test robot connection
		bt.connect();
		
		while( true )
			try {
				ServerHandler n = new ServerHandler( server.accept() );
				vs = new videoStream(n.getIP().toString());
				vs.Start();
				n.start();
				handlers.add( n );
			} catch( IOException e ) {
				Shared.error( "Could not establish connection with host!" );
			}
	}
	
	public static void removeClient( ServerHandler n )
	{
		handlers.remove( n );
	}
	
	public static Vector< HitInformation > request
		( String 		req,
		  InetAddress 	IP )
	{
		Vector< HitInformation > result = new Vector<HitInformation>(0);
		System.out.println( "server request method ");
		for( int x = 0; x < handlers.size(); x++ ){
			if( !handlers.elementAt( x ).getIP().equals( IP ) ){
				HitInformation temp = handlers.elementAt( x ).request( req );
				if( temp != null && !temp.isEmpty() ){
					result.add(temp);
				}else {
					System.out.println("request was null");
				}
			}
		}
		return result;
	}

	public static RobotInformation requestRobotState
		( String 		req,
		  InetAddress 	IP )
	{
		RobotInformation result = new RobotInformation();
		System.out.println( "server request robot state method ");
/*		for( int x = 0; x < handlers.size(); x++ ){
			if( !handlers.elementAt( x ).getIP().equals( IP ) ){
				HitInformation temp = handlers.elementAt( x ).request( req );
				if( temp != null && !temp.isEmpty() ){
					result.add(temp);
				}else {
					System.out.println("request was null");
				}
			}
		}*/
		return result;
	}
	
	public static void moveRobot( String mov ){
		bt.send(mov + "\n" );
	}
	
	public static void main( String args[] ){

		int port = DEFAULT_PORT;
		if( args.length < 1 )
		{
			System.out.println
					( " -= NOTE: No port specified, using the " +
					  "default port of " +
					  DEFAULT_PORT +
					  "." );
		}
		else{
			port = Integer.parseInt( args[0]);
		}
		
		new Server( port );
	}
}
